package com.example.myapplication.screen

import android.content.Context
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch


//1. 创建DataStore实例
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "app_config")

//2. 定义键的名称
val COUNTER = intPreferencesKey("counter")

@Composable
fun DataStroeDemo(padding: PaddingValues?) {

    //3.获取上下文对象
    val context = LocalContext.current.applicationContext

    val scope = rememberCoroutineScope()

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Button(onClick = {
            //开启协程： 把数据写到首选项文件中
            scope.launch {
                context.dataStore.edit { preferences ->
                    preferences[COUNTER] = 20
                }
            }
        }) {
            Text("写数据")
        }

        Button(onClick = {
            scope.launch {
                context.dataStore.data.map { preferences ->
                    preferences[COUNTER] ?: 0
                }
                .collect { value ->
                    println("读取数据：" + value)
                }
            }
        }) {
            Text("读数据")
        }
    }
}
